package com.jiuyin.dianjing.ui.activity.match;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RadioGroup;

import androidx.annotation.Nullable;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.model.MatchGameItemModel;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.util.FileUtils;
import com.jiuyin.dianjing.util.PMUtil;
import com.jiuyin.dianjing.util.ToastUtil;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.util.BGAPhotoHelper;
import me.jessyan.autosize.utils.LogUtils;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_COMPETE_LOGO;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_GAME_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_MATCH_CREATE_TYPE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_MATCH_ENTER_TYPE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_MATCH_TYPE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TYPE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.VALUE_MATCH_TYPE_CREATE;
import static com.jiuyin.dianjing.constant.AppConstant.FOLDER_NAME;
import static com.jiuyin.dianjing.constant.HelperConstant.MATCH_TYPE_CAMPUS;
import static com.jiuyin.dianjing.constant.HelperConstant.MATCH_TYPE_CITY;
import static com.jiuyin.dianjing.constant.HelperConstant.MATCH_TYPE_OPEN_TOURNAMENT;
import static com.jiuyin.dianjing.constant.HelperConstant.MATCH_TYPE_PERSON;
import static com.jiuyin.dianjing.constant.HelperConstant.MATCH_TYPE_TEAM;
import static com.jiuyin.dianjing.constant.HelperConstant.MATCH_WAY_INDEPENDENT_HOST;
import static com.jiuyin.dianjing.constant.HelperConstant.MATCH_WAY_SPONSORED;
import static com.jiuyin.dianjing.constant.HelperConstant.POSITION_DEFAULT;

/**
 * 创建赛事
 */
public class MatchCreateActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;

    @BindView(R.id.rg_match_way)
    RadioGroup rgMatchWay;

    @BindView(R.id.rg_match_type)
    RadioGroup rgMatchType;

    @BindView(R.id.rg_match_enter_type)
    RadioGroup rgMatchEnterType;

    @BindView(R.id.gv_rg_match_select)
    GridView gvRgMatchSelect;

    @BindView(R.id.iv_match_theme)
    ImageView ivTheme;


    /**
     * 赛事类型
     */
    private String mMatchType;

    /**
     * 举办方式
     */
    private String mMatchWay;
    /**
     * 参赛方式
     */
    private String mMatchEnterType;


    private int mSelectPosition = POSITION_DEFAULT;
    private CommonAdapter<MatchGameItemModel> mAdapter;

    private String mGameId;

    private BGAPhotoHelper mPhotoHelper;
    private String path = "";
    private String theme = "";
    private static final int REQUEST_CODE_CHOOSE_PHOTO = 1;
    private static final int REQUEST_CODE_CROP = 2;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_match_create;
    }

    @Override
    protected void initData() {
        getGameList();
    }

    private void getGameList() {
        HashMap<String, Object> params = new HashMap<>();
        params.put(KEY_TOKEN, HelperApplication.getToken());
        params.put(KEY_TYPE, VALUE_MATCH_TYPE_CREATE);
        JSONObject jsonObject = new JSONObject(params);
        getApiHelper().appGetMyCompetitionGameList(jsonObject.toString(), data -> {
            mAdapter = new CommonAdapter<MatchGameItemModel>(MatchCreateActivity.this, R.layout.item_match_create, data) {
                @Override
                protected void convert(ViewHolder viewHolder, MatchGameItemModel item, int position) {
                    viewHolder.setText(R.id.tv_match_create_name, item.getName());
                    ImageView imageView = viewHolder.getView(R.id.img_match_create_icon);
                    Glide.with(MatchCreateActivity.this).load(item.getLogo()).into(imageView);
                    if (position == mSelectPosition) {
                        viewHolder.setBackgroundRes(R.id.ll_game_info_item, R.drawable.item_match_game_select_select_bg);
                    } else {
                        viewHolder.setBackgroundRes(R.id.ll_game_info_item, R.drawable.item_match_game_select_normal_bg);
                    }
                }
            };
            gvRgMatchSelect.setAdapter(mAdapter);
            gvRgMatchSelect.setOnItemClickListener((parent, view, position, id) -> {
                if (mSelectPosition != position) {
                    mSelectPosition = position;
                    mGameId = mAdapter.getItem(position).getGameId();
                    mAdapter.notifyDataSetChanged();
                }
            });
        });
    }

    @Override
    protected void initView() {
        setTitle(R.string.match_create);
        mMatchType = MATCH_TYPE_CAMPUS;
        rgMatchType.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_match_colleges_universities:
                    mMatchType = MATCH_TYPE_CAMPUS;
                    break;
                case R.id.rb_match_city:
                    mMatchType = MATCH_TYPE_CITY;
                    break;
                case R.id.rb_match_public:
                    mMatchType = MATCH_TYPE_OPEN_TOURNAMENT;
                    break;
                default:
                    break;
            }
        });

        mMatchWay = MATCH_WAY_INDEPENDENT_HOST;
        rgMatchWay.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_match_people_hold:
                    mMatchWay = MATCH_WAY_INDEPENDENT_HOST;
                    break;
                case R.id.rb_match_need_sponsor:
                    mMatchWay = MATCH_WAY_SPONSORED;
                    break;
                default:
                    break;
            }
        });

        mMatchEnterType = MATCH_TYPE_PERSON;
        rgMatchEnterType.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_match_enter_people_hold:
                    mMatchEnterType = MATCH_TYPE_PERSON;
                    break;
                case R.id.rb_match_enter_need_sponsor:
                    mMatchEnterType = MATCH_TYPE_TEAM;
                    break;
                default:
                    break;
            }
        });
        ivTheme.setOnClickListener(v -> {
            choosePhoto(REQUEST_CODE_CHOOSE_PHOTO);
        });
        // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
        File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "BGAPhotoPickerTakePhoto");
        mPhotoHelper = new BGAPhotoHelper(takePhotoDir);
    }

    public void choosePhoto(int type) {
        startActivityForResult(mPhotoHelper.getChooseSystemGalleryIntent(), type);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        BGAPhotoHelper.onSaveInstanceState(mPhotoHelper, outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        BGAPhotoHelper.onRestoreInstanceState(mPhotoHelper, savedInstanceState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_CHOOSE_PHOTO) {
                if (data != null) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        startPhotoZoom(uri);
                    }
                }
            } else if (requestCode == REQUEST_CODE_CROP) {
                if (path != null && path.length() != 0) {
                    Bitmap bitmap = BitmapFactory.decodeFile(path);
                    //给头像设置图片源
                    //上传头像
                    ivTheme.setImageBitmap(bitmap);
                    OSSCompletedCallback<PutObjectRequest, PutObjectResult> userCallback = new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                        @Override
                        public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                            theme = request.getObjectKey();
                            Log.d("onValidationSucceeded", "headPortrait: " + theme);

                        }

                        @Override
                        public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                            ToastUtil.showShort(clientException.getMessage());
                        }
                    };
                    String fileName = FileUtils.generateFileName(path);
                    HelperApplication.ossService.asyncPutImage(FOLDER_NAME + fileName, path, userCallback, null);
                }
            }
        } else {
            if (requestCode == REQUEST_CODE_CROP) {
                mPhotoHelper.deleteCameraFile();
                mPhotoHelper.deleteCropFile();
            }
        }
    }

    private void next() {
        if (POSITION_DEFAULT == mSelectPosition) {
            ToastUtil.showShort(R.string.match_game_null);
        } else if (TextUtils.isEmpty(theme)){
            ToastUtil.showShort(R.string.please_upload_the_event_theme);
        }else {
            Bundle bundle = new Bundle();
            bundle.putString(KEY_MATCH_TYPE, mMatchType);
            bundle.putString(KEY_MATCH_CREATE_TYPE, mMatchWay);
            bundle.putString(KEY_MATCH_ENTER_TYPE, mMatchEnterType);
            bundle.putString(KEY_GAME_ID, mGameId);
            bundle.putString(KEY_COMPETE_LOGO, "http://jiuyinesports.com/" + theme);
            goTargetActivity(MatchCreateFillIndependentHostActivity.class, bundle);
        }
    }

    @Override
    public void finish() {
        PMUtil.getInstance().finishAc(MatchCreateFillIndependentHostActivity.class);
        super.finish();
    }


    @OnClick({R.id.tv_game_create_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.tv_game_create_next:
                next();
        }
    }

    private void startPhotoZoom(Uri uri) {
        try {
            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
            String address = sDateFormat.format(new Date());
            if (!FileUtils.isFileExist("")) {
                FileUtils.createSDDir("");
            }

            Uri imageUri = Uri.parse("file:///sdcard/formats/" + address + ".JPEG");
            final Intent intent = new Intent("com.android.camera.action.CROP");

            // 照片URL地址
            intent.setDataAndType(uri, "image/*");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1000);
            intent.putExtra("aspectY", 700);
            // 输出路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            // 输出格式
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            // 不启用人脸识别
            intent.putExtra("noFaceDetection", false);
            intent.putExtra("return-data", false);
            intent.putExtra("fileurl", FileUtils.SDPATH + address + ".JPEG");
            intent.putExtra("outputX", 1000);
            intent.putExtra("outputY", 700);
            path = FileUtils.SDPATH + address + ".JPEG";
            startActivityForResult(intent, REQUEST_CODE_CROP);

        } catch (IOException e) {
            LogUtils.w(e.getMessage());
        }
    }
}
